"""Various utility methods."""

from collections import abc
import datetime
import typing

from cki_lib import misc

from . import secrets

DEFAULT_DELTA = datetime.timedelta(days=30)
DEFAULT_INTERVAL = datetime.timedelta(days=365)


def all_tokens(token_types: abc.Container[str]) -> list[str]:
    """Return names of secrets for given token types."""
    return [
        k for k, v in secrets.read_secrets_file().items()
        if misc.get_nested_key(v, 'meta/token_type') in token_types
    ]


def split_token_name(token_name: str) -> tuple[str, str]:
    """Return token group and version."""
    return token_name.partition('/')[::2]


def tz(token_data: dict[str, typing.Any], field: str) -> datetime.datetime | None:
    """Return a timestamp for the given field."""
    timestamp = misc.get_nested_key(token_data, f'meta/{field}')
    return misc.datetime_fromisoformat_tz_utc(timestamp) if timestamp else None


def too_old(
    timestamp: datetime.datetime | None,
    interval: datetime.timedelta = datetime.timedelta(0),
) -> bool:
    """Check if the token is too old."""
    if not timestamp:
        return False
    return timestamp + interval < misc.now_tz_utc() + DEFAULT_DELTA


def confirm(prompt: str) -> bool:
    """Prompt user a yes or no question, returning its boolean value. Defaults to False."""
    answer = input(prompt + " [y/N]: ")
    return str(answer).lower() in {"y", "yes"}
